package com.nit.elasticsearch.moudles.jd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nit.elasticsearch.moudles.jd.entity.Content;
import com.nit.elasticsearch.moudles.jd.service.Jdservice;
import com.nit.elasticsearch.moudles.jd.utils.HtmlParseUtil;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author :fjw
 * @description:TODO
 * @date :2020/11/14 12:26
 */
@Service
public class JdServiceImpl implements Jdservice {

	@Autowired
	private RestHighLevelClient client;
	@Autowired
	private ObjectMapper om;


	//1.解析并插入数据
	@SneakyThrows
	public Boolean parseContent(String keyword, int page) {
		List<Content> contents = HtmlParseUtil.parseJD(keyword, page);
		BulkRequest bulkRequest = new BulkRequest().timeout(TimeValue.timeValueSeconds(20));
		for (Content content : contents) {
			bulkRequest.add(new IndexRequest("jd").source(om.writeValueAsString(content),XContentType.JSON));
		}
		BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
		return !bulk.hasFailures();
	}
	//2.获取数据实现搜索+高亮
	@SneakyThrows
	public List<Map<String,Object>> search(String keyword, int from, int size) {
		//构建请求
		SearchRequest searchRequest = new SearchRequest("jd");
		//搜索构建器
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().timeout(TimeValue.timeValueSeconds(60));
		searchSourceBuilder.from(from);
		searchSourceBuilder.size(size);
		searchSourceBuilder.query(QueryBuilders.termQuery("title",keyword));
		//设置搜索高亮字段
		searchSourceBuilder.highlighter(new HighlightBuilder().field("title").preTags("<span style='color:red'>").postTags("</span>")
				//多个高亮显示
				.requireFieldMatch(false));
		//放入查询条件
		searchRequest.source(searchSourceBuilder);
		//执行搜索
		SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
		//解析结果
		ArrayList<Map<String,Object>> list = new ArrayList<>();
		for (SearchHit hit : response.getHits().getHits()) {
			Map<String, HighlightField> highlightFields = hit.getHighlightFields();
			HighlightField title = highlightFields.get("title");
			Map<String, Object> sourceAsMap = hit.getSourceAsMap();
			//解析高亮的字段，
			if(ObjectUtil.isNotNull(title)) {
				Text[] fragments = title.getFragments();
				StringBuilder newTitle = new StringBuilder();
				for (Text text : fragments) {
					newTitle.append(text);
				}
				sourceAsMap.put("title",newTitle.toString());//将原来的字段换位我们高亮的字段
			}
			list.add(sourceAsMap);
		}
		return list;
	}




}
